package com.huika.dealontop.control.myinfo.activity;

import android.content.Intent;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;

import com.android.volley.Response;
import com.google.gson.reflect.TypeToken;
import com.huika.dealontop.GlobalApp;
import com.huika.dealontop.R;
import com.huika.dealontop.config.Constants;
import com.huika.dealontop.config.UrlConstants;
import com.huika.dealontop.control.base.extend.ActionBarHelper;
import com.huika.dealontop.control.base.extend.BaseActionBarActivity;
import com.huika.dealontop.control.myinfo.adapter.CouponListAdapter;
import com.huika.dealontop.control.myinfo.holder.OrderDetailBasicInfoHolder;
import com.huika.dealontop.control.nearby.activity.RefundApplyActivity;
import com.huika.dealontop.control.pay.activity.ChoosePayModesActivity;
import com.huika.dealontop.control.pay.utils.BasePay;
import com.huika.dealontop.support.domain.OrderDetailBean;
import com.huika.dealontop.support.http.FormResultRequest;
import com.huika.dealontop.support.http.JSONWrapAjaxParams;
import com.huika.dealontop.support.http.RequestResult;
import com.huika.dealontop.utils.UIUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Author: Victor Wu <br/>
 * Email: victor-wu*foxmail.com <br/>
 * Time: 2015/11/19 15:35 <br/>
 * Description: 订单详情
 */
public class OrderDetailActivity extends BaseActionBarActivity implements Response.Listener<RequestResult<List<OrderDetailBean>>> { //

    public static final String ORDER_ID = "orderID";

    private String orderID;

    private ListView mLvContent;
    private CouponListAdapter couponListAdapter;
    private OrderDetailBasicInfoHolder mBasicInfoHolder;
    private OrderDetailBean mOrderDetailBean;


    private int orderState;

    protected void onContentViewCreate() {
    }

    @Override
    public void setRootView() {
        setContentView(R.layout.activity_order_detail);

        Intent intent = getIntent();
        if (intent != null) {
            orderID = intent.getStringExtra(ORDER_ID);
        }

        ActionBarHelper actionBarHelper = getActionBarHelper();
        actionBarHelper.setTitleMsg(UIUtils.getString(R.string.order_detail_title));
        actionBarHelper.setOnRightClickListener(this);
    }

    @Override
    protected void initWidget() {
        mLvContent = (ListView) findViewById(R.id.lv_order_detail_content);

        mBasicInfoHolder = new OrderDetailBasicInfoHolder(this);
        mLvContent.addHeaderView(mBasicInfoHolder.getRootView(), null, false);
        mLvContent.addFooterView(getFootView(), null, false);

        couponListAdapter = new CouponListAdapter(this);
        mLvContent.setAdapter(couponListAdapter);
    }

    @Override
    protected void onResume() {
        super.onResume();
        //开始访问网络数据
        startLoadData();
    }

    private void startLoadData() {
        JSONWrapAjaxParams ajaxParams = new JSONWrapAjaxParams();
        ajaxParams.putCommonTypeParam("userID", GlobalApp.getInstance().getUserId());
        ajaxParams.putCommonTypeParam("orderID", orderID);
        FormResultRequest<List<OrderDetailBean>> loginRequest = new FormResultRequest(UrlConstants.ORDER_DETAIL, this, this,
                new TypeToken<RequestResult<List<OrderDetailBean>>>() {
                }.getType());
        loginRequest.setRequestParams(ajaxParams);
        showLoadingDialog("");
        executeRequest(loginRequest);
    }

    @Override
    public void onResponse(RequestResult<List<OrderDetailBean>> requestResult) {
        dismissLoadingDialog();
        if (requestResult != null && (mOrderDetailBean = requestResult.getRs().get(0)) != null) {
            refreshUI(mOrderDetailBean);
        }
    }

    public void refreshUI(OrderDetailBean orderDetailBean) {

        initOrderState();

        mBasicInfoHolder.setData(orderDetailBean);
        couponListAdapter.setGroup(orderDetailBean.getData());

        refreshButton();

    }

    private Button mFootBtn;

    public View getFootView() {
        View view = View.inflate(UIUtils.getContext(), R.layout.order_detail_foot_btn, null);
        mFootBtn = (Button) view.findViewById(R.id.btn_order_detail_foot_btn);
        return view;
    }

    private void refreshButton() {

        mFootBtn.setVisibility(TextUtils.isEmpty(mOrderDetailBean.getActionHolder().btnStr) ? View.GONE : View.VISIBLE);
        mFootBtn.setText(mOrderDetailBean.getActionHolder().btnStr);

        ActionBarHelper actionBarHelper = getActionBarHelper();
        actionBarHelper.setRightMsg(mOrderDetailBean.getActionHolder().btnStr);

        if (mOrderDetailBean.getActionHolder().action != null) {
            mFootBtn.setEnabled(true);
            mFootBtn.setOnClickListener(this);
        } else {
            mFootBtn.setEnabled(false);
        }

    }

    @Override
    public void widgetClick(View v) {
        int id = v.getId();
        if (id == R.id.btn_order_detail_foot_btn
                || id == R.id.right) {
            if (orderState != 1) {
                startActivity(mOrderDetailBean.getActionHolder().action);
            } else {
                getPaymentOrderId();
            }
        }
        super.widgetClick(v);
    }


    /**
     * 评论意图
     */
    private Intent getCommentIntent() {
        Intent intent = new Intent(this, EvaluateActivity.class);
        intent.putExtra(Constants.MERCHANTID, mOrderDetailBean.getMerchantID());
        intent.putExtra(Constants.PRODUCTID, mOrderDetailBean.getProductID());
        intent.putExtra(Constants.PAY_ORDERID, mOrderDetailBean.getOrderID());
        intent.putExtra(Constants.SKUID, mOrderDetailBean.getSkuID());
        return intent;
    }

    /**
     * 支付意图
     *
     * @return
     */
    private Intent getPayIntent() {
        // TODO 去支付
        Intent intent = new Intent(this, ChoosePayModesActivity.class);
        intent.putExtra(BasePay.PAYORDERNO, mOrderDetailBean.getPaymentOrderId());
        intent.putExtra(BasePay.ORDERNO, mOrderDetailBean.getOrderID());
        intent.putExtra(BasePay.TOTALMONEY, mOrderDetailBean.getTotalPrice());
        return intent;
    }

    private void getPaymentOrderId(){
        JSONWrapAjaxParams ajaxParams = new JSONWrapAjaxParams();
        ajaxParams.putCommonTypeParam("userID", GlobalApp.getInstance().getUserId());
        ajaxParams.putCommonTypeParam("orderID", orderID);
        FormResultRequest<Map<String,String>> loginRequest = new FormResultRequest(UrlConstants.REPAYMENT, new Response.Listener<RequestResult<Map<String,String>>>() {
            @Override
            public void onResponse(RequestResult<Map<String,String>> requestResult) {
                dismissLoadingDialog();
                Intent intent = new Intent(OrderDetailActivity.this, ChoosePayModesActivity.class);
                intent.putExtra(BasePay.PAYORDERNO, requestResult.getRs().get("paymentOrderId"));
                intent.putExtra(BasePay.ORDERNO, mOrderDetailBean.getOrderID());
                intent.putExtra(BasePay.TOTALMONEY, mOrderDetailBean.getTotalPrice());
                startActivity(intent);
            }
        }, this,
                new TypeToken<RequestResult<Map<String,String>>>() {
                }.getType());
        loginRequest.setRequestParams(ajaxParams);
        showLoadingDialog("");
        executeRequest(loginRequest);
    }

    /**
     * 退款意图
     *
     * @return
     */
    public Intent getRefundIntent() {
        Intent intent = new Intent(this, RefundApplyActivity.class);
        intent.putParcelableArrayListExtra(RefundApplyActivity.REFUND_ARRAY, mOrderDetailBean.getData());
        intent.putExtra(RefundApplyActivity.REFUND_ORDERID, orderID);
        return intent;
    }

    private void initOrderState() {
        //(1.待付款 2.未使用 3.已使用 4.已退款 5.已过期6.已取消)
        //待付款、未使用、已过期、已使用、已退款、退款中
        orderState = mOrderDetailBean.getOrderStatus();

        //////////////////////////////接口不处理，只能客户端处理了...///////////////////////////////////////////
        // 规则一 ： 只要所有团购券中含有一张或以上 “未使用” 状态的团购券 ---->  订单状态为 “未使用”
        // 规则二 ： 当规则一不存在，只要所有团购券中含有一张或以上 “已使用” 状态的团购券 ---->  订单状态为 “已使用”
        // 总结： 优先级：未使用 < 已使用 < 其他
        ArrayList<OrderDetailBean.DataBean> couponList = mOrderDetailBean.getData();
        if (couponList != null) {
            //检查 已使用
            used:
            for (OrderDetailBean.DataBean item : couponList) {
                if (item.getCouponStatus() == 3) { //团购券 已使用
                    orderState = 3;
                    break used;
                }
            }

            //检查 未使用
            unused:
            for (OrderDetailBean.DataBean item : couponList) {
                if (item.getCouponStatus() == 2) {  //团购券 未使用
                    orderState = 2;
                    break unused;
                }
            }
        }
        /////////////////////////////////////////////////////////////////////////

        OrderDetailBean.OrderStateActionHolder actionHolder = new OrderDetailBean.OrderStateActionHolder();
        if (1 == orderState) {
            actionHolder.stateStr = UIUtils.getString(R.string.myorder_list_filter_nopay);
            actionHolder.btnStr = UIUtils.getString(R.string.to_pay);
            actionHolder.action = getPayIntent();
        }
        if (2 == orderState) { //未使用
            boolean Unused = false;
            actionHolder.stateStr = UIUtils.getString(R.string.myorder_list_filter_nouse);
            //注：未使用订单状态比较特殊：
            //当订单状态为2（未使用） ， 需要遍历 所有团购券中是否含有未使用的
            w:
            for (OrderDetailBean.DataBean item : mOrderDetailBean.getData()) {
                if (item.getCouponStatus() == 2) { //  2未使用，3已使用，4：退款中，5：已退款，6已过期（可退款,扣订单支付金额20%，可消费)
                    Unused = true;
                    break w;
                }
            }
            if (Unused && !mOrderDetailBean.isSale()) { /** add by victor wu (2016.1.22) */
                actionHolder.btnStr = UIUtils.getString(R.string.myorder_list_filter_backprice);
                actionHolder.action = getRefundIntent();
            } else {
                //所有团购券中 没有未使用的  就不需要操作按钮
                actionHolder.btnStr = null;
                actionHolder.action = null;
            }
        }
        if (3 == orderState) {
            actionHolder.stateStr = UIUtils.getString(R.string.myorder_list_has_use);
            int iscomment = mOrderDetailBean.getIscomment();
            if (iscomment == 0) {//iscomment: 评论状态 （0未评价，1已评价）
                actionHolder.btnStr = UIUtils.getString(R.string.to_evaluate);
                actionHolder.action = getCommentIntent();
            } else if (iscomment == 1) {
                //按钮只显示文字 没有操作动作
                //actionHolder.btnStr = UIUtils.getString(R.string.has_evaluated);
            }
        }
        if (4 == orderState) {
            actionHolder.stateStr = UIUtils.getString(R.string.myorder_list_has_refund);
            //isReturn不用了 <2015-12-4>
           /* int isReturn = mOrderDetailBean.getIsReturn(); //(0正常，1退款中，2已退款，3审核未通过）
            if(isReturn == 1){
                actionHolder.stateStr = UIUtils.getString(R.string.myorder_list_refuning);
            }else if(isReturn == 3){
                actionHolder.stateStr = UIUtils.getString(R.string.refund_failed);
            }else{
                actionHolder.stateStr = UIUtils.getString(R.string.myorder_list_has_refund);
            }*/
            //退款中订单 隐藏底部操作按钮
        }
        if (5 == orderState && !mOrderDetailBean.isSale()) { /** add by victor wu (2016.1.22) */
            actionHolder.stateStr = UIUtils.getString(R.string.myorder_list_has_expired);
            actionHolder.btnStr = UIUtils.getString(R.string.myorder_list_filter_backprice);
            actionHolder.action = getRefundIntent();
        }
        if (6 == orderState) {
            actionHolder.stateStr = UIUtils.getString(R.string.myorder_list_filter_alreadycancle);
        }
        mOrderDetailBean.setActionHolder(actionHolder);
    }

}
